package com.wen.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wen.common.utils.PageUtils;
import com.wen.common.utils.Query;
import com.wen.gulimall.product.dao.CategoryDao;
import com.wen.gulimall.product.entity.CategoryEntity;
import com.wen.gulimall.product.service.CategoryBrandRelationService;
import com.wen.gulimall.product.service.CategoryService;
import com.wen.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> list = baseMapper.selectList(null);
        //2.组装成父子的树形结构
        //1)、先找出所有的一级父类
        List<CategoryEntity> level1Menus = list.stream().filter(item ->
                item.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, list));
            return menu;
        }).sorted((menu1, menu2) -> {
            return menu1.getSort() - menu2.getSort();
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(Long[] catIds) {
        //TODO 需要补充删除的逻辑
        baseMapper.deleteBatchIds(Arrays.asList(catIds));
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCageory(category.getCatId(), category.getName());
    }

    @Override
    public List<CategoryEntity> getLavel1Categorys() {
        long l = System.currentTimeMillis();
        List<CategoryEntity> entityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));

        return entityList;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() throws InterruptedException {
        /**
         * 1、空结果缓存:解决缓存穿透
         * 2、设置过期时间(加随机值):经济绝缓存雪崩
         * 3、枷锁:解决缓存击穿
         */

        //1、加入缓存逻辑
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");

        if (StringUtils.isEmpty(catalogJSON)) {
            //2、缓存中没有，查询数据库

            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();

            return catalogJsonFromDb;
        }

        //转为我们指定的对象
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        System.out.println("缓存命中");
        return result;

    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() throws InterruptedException {
        //生成唯一标识
        String uuid = UUID.randomUUID().toString();
        //进行抢锁操作
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);

        //没抢到锁则间隔100ms继续进行枪锁操作
        while (!ifAbsent) {
            System.out.println("获取分布式失败等待重试");
            Thread.sleep(100);
            ifAbsent = redisTemplate.opsForValue().setIfAbsent("lock", uuid);
        }


        System.out.println("获取分布式成功");
        Map<String, List<Catelog2Vo>> dataFromDb = new HashMap<>();
        try {
            dataFromDb = getDataFromDb();
        } finally {
            String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
            //删除锁

            redisTemplate.execute(new DefaultRedisScript<Integer>(script, Integer.class), Arrays.asList("lock"), uuid);
            System.out.println("删除锁成功");
        }


        return dataFromDb;


    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() throws InterruptedException {
        //1、占分布式锁。去redis占坑
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        System.out.println("获取锁成功");
        Map<String, List<Catelog2Vo>> dataFromDb = new HashMap<>();
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }



        return dataFromDb;


    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        //1、查询所有一级分类
        List<CategoryEntity> lavel1Categorys = getParent_cid(entityList, 0L);
        //2、封装数据
        Map<String, List<Catelog2Vo>> map = lavel1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类，查到这个以及分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(entityList, v.getCatId());
            //分装指定的结果
            List<Catelog2Vo> collect = null;
            if (categoryEntities != null) {
                collect = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1、找出当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(entityList, l2.getCatId());
                    if (level3Catelog != null) {
                        //2、封装成指定格式
                        List<Catelog2Vo.Catelog3Vo> catelog3VoList = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());

                        catelog2Vo.setCatalog3List(catelog3VoList);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        //3、查到的数据在放入缓存,将对象转为json放在缓存中
        String s = JSON.toJSONString(map);
        redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return map;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        /**
         * 1、将数据库的多次查询变为一次
         *
         */
        synchronized (this) {
            return getDataFromDb();
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> entityList, Long parent_cid) {
        List<CategoryEntity> collect = entityList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;

    }
    //  return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));


    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        System.out.println("paths = " + paths);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 递归查找所有菜单的子菜单
     */
    private List<CategoryEntity> getChildrens(CategoryEntity categoryEntity, List<CategoryEntity> all) {
        //找出对应的下级菜单
        List<CategoryEntity> collect = all.stream().filter(item -> categoryEntity.getCatId().equals(item.getParentCid()))
                .map(
                        item -> {
                            //递归
                            item.setChildren(getChildrens(item, all));
                            return item;
                        }
                ).sorted((item1, item2) -> {
                    return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
                }).collect(Collectors.toList());
        return collect;
    }

}